package com.liangsui.mss.mq.service.impl;

import com.alibaba.fastjson.JSON;
import com.liangsui.mss.mq.dto.BaseMqDto;
import com.liangsui.mss.mq.service.RocketMqService;
import com.liangsui.mss.utils.ValidationUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;

/**
 * rocketMqServiceImpl
 *
 * @author zhangjiawei
 * @email 1533167396@qq.com
 * @date 2022/12/8 17:37
 */
@Slf4j
@Service
public class RocketMqServiceImpl implements RocketMqService {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public void sendDelay(String topic, BaseMqDto<?> data, int delayLevel) {
        ValidationUtils.notNullParam(topic);
        ValidationUtils.notNullParam(data);
        ValidationUtils.notNullParam(data.getData());
        ValidationUtils.isTrue(delayLevel >= 0, "延迟级别参数必须大于等于0");
        rocketMQTemplate.asyncSend(topic, MessageBuilder.withPayload(data).build(), new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                log.info("sendDelayed - onSuccess - topic:{} data:{} sendResult:{}:",
                        topic, JSON.toJSONString(data), JSON.toJSONString(sendResult));
            }

            @Override
            public void onException(Throwable throwable) {
                log.info("sendDelayed - onException - topic:{} data:{} e:",
                        topic, JSON.toJSONString(data), throwable);
            }
        }, 5000, delayLevel);
    }
}
